//
//  TXSwiftAbstractHeaderView.swift
//  TXiOSDemoApp
//
//  Created by xicheng on 16/11/22.
//  Copyright © 2016年 xicheng. All rights reserved.
//

import UIKit


public enum TXSwiftHeaderViewStatus:String {
  case normal // 正常
  
  case prepareToRefresh // 预备刷新
  
  case refreshing // 刷新中

}



open class TXSwiftAbstractHeaderView: UIView {

  weak var scrollView:UIScrollView? = nil
  var action:(()->Void)? = nil
  var TXHeadKVOContext = "TXSwiftHeaderView"
  var activityView: UIActivityIndicatorView?
  
  public var headerViewStatus:TXSwiftHeaderViewStatus = .normal {
  
    didSet{
    
      switch headerViewStatus {
      case .normal:
        break
      case .prepareToRefresh:
        break
      case .refreshing:
        break
      }
      self.headerViewStatusListener?(headerViewStatus)
    }
  
  }
  
  private lazy var headerViewStatusListener:((TXSwiftHeaderViewStatus)->Void)? = {
    [unowned self] in
    return self.configHeaderViewStatusListener()
  }()
  
  private lazy var TX_headerPullHeight:CGFloat = {
    [unowned self] in
    return self.configRefreshPullHeight()
  }()
   
  

  
  public required init(action:@escaping (()->Void),frame: CGRect) {
    super.init(frame: frame)
    self.prepareView()
    self.action = action
  }
  
  required public init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  
  open func configRefreshPullHeight()->CGFloat{
    return 50.0
  }
  
  open func configHeaderViewStatusListener()->((TXSwiftHeaderViewStatus)->Void)? {
    return nil
  }
  
  
  open func prepareView(){
    
  }
  
  
  func startAnimation(){
    
  }
  
  func stopAnimation(){
    
    UIView.animate(withDuration: 0.25, animations: { 
      [unowned self] in
      
      guard let scrollView = self.scrollView else {
        return
      }
      
//      if (abs(scrollView.contentOffset.y) >= self.TX_headerPullHeight){
        scrollView.contentInset = UIEdgeInsetsMake(scrollView.contentInset.top - self.TX_headerPullHeight, 0, scrollView.contentInset.bottom, 0)
//      }
      }) { [unowned self](flag) in
        self.headerViewStatus = .normal
        self.scrollView?.tx_refreshStatus = .normal
    }
    
  }
  
  
  open override func layoutSubviews() {
    super.layoutSubviews()
    
  }
  
  
  open override func willMove(toSuperview newSuperview: UIView?) {
    super.willMove(toSuperview: newSuperview)
    superview?.removeObserver(self, forKeyPath: TX_contentOffsetKeyPath, context: &TXHeadKVOContext)
    
    if let scrollView = newSuperview as? UIScrollView {
      self.scrollView = scrollView
      newSuperview?.addObserver(self, forKeyPath: TX_contentOffsetKeyPath, options: .initial, context: &TXHeadKVOContext)
    }
    
  }
  
  open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    
   
    
    guard let scrollView = self.scrollView else {
      return
    }
    
    let offSet_Y = scrollView.contentOffset.y
    // MARK: 100需要算出来
    guard offSet_Y < 100 else {
      return
    }
    
    guard let action = self.action else {
      return
    }
    
    if self.scrollView?.tx_refreshStatus == TXRefreshStatus.refresh {
      if self.headerViewStatus != .refreshing {
        TXLogError("ScrollView与HeaderView状态不匹配：\(self.headerViewStatus)")
      }
      
      return
    }
    
   
    
    TXLogDebug("HeaderView:\(offSet_Y)")
    
    
    if offSet_Y < (-TX_headerPullHeight - scrollView.contentInset.top) {
      
      let draggingFlag = scrollView.isDragging
      if draggingFlag {
        if self.headerViewStatus == .normal {
          self.configSelf(WithStatus: .prepareToRefresh)
        }
      }else {
        // MARK: 配置刷新
        self.configSelf(WithStatus: .refreshing)
        if scrollView.tx_refreshStatus != TXRefreshStatus.refresh {
          scrollView.tx_refreshStatus = TXRefreshStatus.refresh
          action()
        }
        
        UIView.animate(withDuration: 0.25, animations: { 
          [unowned self] in
          guard let scrollView = self.scrollView else{
            return
          }
          scrollView.contentInset = UIEdgeInsetsMake(self.TX_headerPullHeight + scrollView.contentInset.top, 0, scrollView.contentInset.bottom, 0)
        })
        
        
      }
    }else {
      // Mark:
      self.configSelf(WithStatus: .normal)
    }
    
    
  }
  
  private func configSelf(WithStatus status:TXSwiftHeaderViewStatus){
    if self.headerViewStatus != status {
      self.headerViewStatus = status
      TXLogInfo("更换为：\(status)")
    }
  }
  
  
  deinit {
    if let parentView = superview as? UIScrollView {
      parentView.removeObserver(self, forKeyPath: TX_contentOffsetKeyPath, context: &TXHeadKVOContext)
    }
  }

}
